package top.yangyitao.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.google.common.util.concurrent.RateLimiter;
import top.yangyitao.annotation.RateLimit;

public class RateLimitInterceptor implements HandlerInterceptor {
 
    private final static Logger logger = LoggerFactory.getLogger(RateLimitInterceptor.class);
    
    //每s产生2000个令牌
    RateLimiter rateLimiter = RateLimiter.create(2000);
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //如果是SpringMVC请求
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);
            if(rateLimit != null) {
            	logger.info("rateLimit intercept method...");
            	if (!rateLimiter.tryAcquire(rateLimit.value(), rateLimit.timeOutUnit())) {
            		throw new Exception("系统繁忙，新稍后再试!");
                 }
            }
        }
        return true;
    }

}
